﻿using System;
using System.Web;
using System.Web.Mvc;

namespace mForum.Web.Common.ActionFilters
{
    using mForum.Core.Common;
    using mForum.Core.Messages.UserServiceMessages;
    using mForum.Core.Service;

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class UpdateUserLastActivityAttribute : FilterAttribute, IResultFilter
    {
        public UpdateUserLastActivityAttribute(IUserService userService)
        {
            Check.Argument.IsNotNull(userService, "userService");

            UserService = userService;
        }

        public IUserService UserService
        {
            get;
            private set;
        }

        public void OnResultExecuting(ResultExecutingContext filterContext)
        {

        }

        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            Check.Argument.IsNotNull(filterContext, "filterContext");

            string username = filterContext.HttpContext.User.Identity.IsAuthenticated ? filterContext.HttpContext.User.Identity.Name : null;

            if (!string.IsNullOrEmpty(username))
            {

                UserService.UpdateLastActivity(new UpdateLastActivityRequest() { Username = username });
            }
        }
    }
}
